<template>
  <div>
    <el-dialog
      title="新增流程日志节点"
      :visible.sync="show"
      width="30%"
      append-to-body
      @close="handleClickDeal('cancel')"
    >
      <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="节点名称" prop="taskDefKey">
              <el-select size="small" class="width100" clearable
                         v-model="form.taskDefKey" filterable
                         placeholder="请选择节点"
                         @change="chooseNodeFuc"
                         :disabled="type=='check'">
                <el-option
                  v-for="item in taskKeyList"
                  :key="item._id"
                  :label="item._name"
                  :value="item._id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点类型" prop="nodeType">
              <el-select size="small" class="width100" clearable
                         v-model="form.nodeType" filterable
                         placeholder="请选择节点类型"
                         :disabled="type=='check'">
                <el-option
                  v-for="item in nodeTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="表达式">
              <el-input v-model="form.expression" aria-placeholder="控制历史记录节点是否显示"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort" class="width100">
              <el-input v-model="form.sort" :disabled="type=='check'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.nodeType == '3'">
          <el-col :span="24">
            <el-form-item label="上级节点" prop="nodeType">
              <el-select size="small" class="width100" clearable
                         v-model="form.parentTaskDefKey" filterable
                         placeholder="请选择节点类型"
                         :disabled="type=='check'">
                <el-option
                  v-for="item in taskKeyList"
                  :key="item._id"
                  :label="item._name"
                  :value="item._id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="isLoading" plain @click="handleClickDeal('cancel')">取 消</el-button>
        <el-button type="primary" :loading="isLoading" @click="handleClickDeal('submit')"
                   v-if="type !='check'">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import step from '@/api/wf/step'
  import msgUtil from '@/utils/msgUtil'
  import {getXml} from '@/api/wf/process'

  export default {
    name: "field_detail",
    props: {
      postDetail: {
        show: false,
        type: '',
        params: {}
      },
    },
    watch: {
      postDetail(value) {
        this.show = value.show
        this.procDefKey = value.params.procDefKey ? value.params.procDefKey : ''
        this.detailId = value.params.detailId ? value.params.detailId : ''
        this.xmlId = value.params.xmlId ? value.params.xmlId : ''
        this.type = value.type
        this.init()
      }
    },
    data() {
      return {
        show: false,
        procDefKey: '',
        type: 'add',
        isLoading: false,
        detailId: '',
        form: {
          taskDefKey: '',
          nodeName: '',
          nodeType: '',
          expression: '',
          sort: '',
          parentTaskDefKey: ''
        },
        taskKeyList: [],
        nodeTypeList: [{label: '用户节点', value: 1}, {label: '普通会签节点', value: 2}, {label: '会签分支', value: 3}],
        formRules: {
          taskDefKey: [
            {required: true, message: '请选择' + '节点', trigger: 'change'},
          ],
          nodeType: [
            {required: true, message: '请选择' + '节点类型', trigger: 'change'},
          ],
        }
      }
    },
    methods: {
      init() {
        this.getTaskNode()
        if (this.type != 'add') {
          this.getDetail()
        }
      },
      getTaskNode() {
        getXml(this.xmlId).then(res => {
          let xml = res.data
          xml = xml.replace(/<bpmn:process id="\w+">/, `<bpmn:process id="${this.procDefKey}">`)
          let xmlObj = this.$x2js.xml2js(xml)
          this.taskKeyList = []
          if (!xmlObj.definitions || !xmlObj.definitions.process) {
            return;
          }

          if (xmlObj.definitions.process.userTask && xmlObj.definitions.process.userTask.length > 0) {
            this.taskKeyList = xmlObj.definitions.process.userTask
          }
          console.log(xmlObj.definitions.process)
          const transaction = xmlObj.definitions.process.transaction
          if (transaction) {
            let item = {
              _id: transaction._id,
              _name: transaction._name,
            }
            this.taskKeyList.push(item)
            // ps: 测试结果，如果只有一个节点的话，是个对象多个节点类型是Array
            if (transaction.userTask && transaction.userTask.length > 0) {
              if (transaction.userTask instanceof Array) {
                transaction.userTask.forEach(it => {
                  item = {
                    _id: it._id,
                    _name: it._name,
                    _pid: transaction._id
                  }
                  this.taskKeyList.push(item)
                })
              } else {
                item = {
                  _id: transaction.userTask._id,
                  _name: transaction.userTask._name,
                  _pid: transaction._id
                }
                this.taskKeyList.push(item)
              }
            }
          }
        })
      },
      chooseNodeFuc(id) {
        var obj = this.taskKeyList.find(item => {
          return item._id === id
        })
        if (obj) {
          this.form.nodeName = obj._name
          if (obj._pid) {
            this.form.nodeType = 3
            this.form.parentTaskDefKey = obj._pid
          } else {
            this.form.nodeType = 1
            this.form.parentTaskDefKey = ''
          }
        }
      },
      getDetail() {
        step.findOne(this.detailId).then(response => {
          this.form = response.data
        })
      },
      clearnForm() {
        this.form = {
          taskDefKey: '',
          nodeName: '',
          nodeType: '',
          expression: '',
          parentTaskDefKey: '',
          sort: '',
        }
      },
      submitDetail() {
        if (this.type === 'add') {
          step.add(this.form).then(response => {
            msgUtil.success2('保存成功!')
          }).finally(() => {
            this.isLoading = false
            this.clearnForm()
            this.$emit("reloadList")
          })
        } else if (this.type === 'edit') {
          step.edit(this.form).then(res => {
            msgUtil.success2('修改成功')
          }).finally(() => {
            this.isLoading = false
            this.clearnForm()
            this.$emit("reloadList")
          })
        }
      },
      handleClickDeal(type) {
        switch (type) {
          case 'submit':
            this.$refs['form'].validate((valid) => {
              if (valid) {
                this.show = false
                this.isLoading = true
                this.form.procDefKey = this.procDefKey
                this.submitDetail()
              }
            })
            break
          case 'cancel':
            this.show = false
            this.clearnForm()
            break
        }
      },
    }
  }
</script>

<style scoped>

</style>
